<template>
  <div class="m-3">
    <n-collapse :expanded-names="1">
      <n-collapse-item title="修改密码" :name="1">
        <n-grid x-gap="12" :cols="3">
          <n-gi :span="1">
          </n-gi>
          <n-gi :span="1">
            <n-form ref="formRef"  :model="model" :rules="rules">
              <n-form-item path="password" label="旧密码">
                <n-input v-model:value="model.password" maxlength="20"  show-password-on="mousedown" type="password" @keydown.enter.prevent />
              </n-form-item>
              <n-form-item path="password" label="新密码">
                <n-input
                    v-model:value="model.newPassword"
                    type="password"
                    maxlength="20"
                    show-password-on="mousedown"
                    @input="handlePasswordInput"
                    @keydown.enter.prevent
                />
              </n-form-item>
              <div class="intensity">
                <span class="psdText">密码强度</span>
                <span
                    class="line"
                    :class="[level.includes('low') ? 'low' : '']"
                ></span>
                <span
                    class="line"
                    :class="[level.includes('middle') ? 'middle' : '']"
                ></span>
                <span
                    class="line"
                    :class="[level.includes('high') ? 'high' : '']"


                ></span>
                <div class="warningtext">
                  密码应由8-16位数字、字母、符号组成
                </div>
              </div>
              <n-form-item class="mt-3"
                  ref="rPasswordFormItemRef"
                  first
                  path="reenteredPassword"
                  label="重复密码"
              >
                <n-input
                    v-model:value="model.reenteredPassword"
                    :disabled="!model.newPassword"
                    maxlength="20"
                    show-password-on="mousedown"
                    type="password"
                    @keydown.enter.prevent
                />
              </n-form-item>
              <n-row :gutter="[0, 24]">
                <n-col :span="24">
                  <div style="display: flex; justify-content: flex-end">
                    <n-button
                        :disabled="model.password === null"
                        type="primary"
                        @click="handleValidateButtonClick"
                    >
                      确认修改
                    </n-button>
                  </div>
                </n-col>
              </n-row>
            </n-form>
          </n-gi>
        </n-grid>
      </n-collapse-item>
    </n-collapse>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'
import {
  FormInst,
  FormItemInst,
  FormItemRule,
  useMessage,
  FormRules
} from 'naive-ui'

interface ModelType {
  newPassword: string | null
  password: string | null
  reenteredPassword: string | null
}

export default defineComponent({
  setup () {
    const formRef = ref<FormInst | null>(null)
    const rPasswordFormItemRef = ref<FormItemInst | null>(null)
    const message = useMessage()
    let level = ref([])
    const modelRef = ref<ModelType>({
      newPassword: null,
      password: null,
      reenteredPassword: null
    })
    function validatePasswordStartWith (
        rule: FormItemRule,
        value: string
    ): boolean {
      return (
          !!modelRef.value.newPassword &&
          modelRef.value.newPassword.startsWith(value) &&
          modelRef.value.newPassword.length >= value.length
      )
    }
    function validatePasswordSame (rule: FormItemRule, value: string): boolean {
      return value === modelRef.value.newPassword
    }
    function checkPassword(value) {
      level.value = []
      // if (!value) {
      //   return '密码不能为空'
      // }
      // if (value.length < 8) {
      //   level.value.push('low')
      // }
      // if (value.length > 16) {
      //   return '密码不大于16位'
      // }
      // 校验是数字
      const regex1 = /^\d+$/
      // 校验字母
      const regex2 = /^[A-Za-z]+$/
      // 校验符号
      const regex3 =
          /^[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、]+$/
      if (regex1.test(value)) {
        level.value.push('low')
      } else if (regex2.test(value)) {
        level.value.push('low')
      } else if (regex3.test(value)) {
        level.value.push('low')
      } else if (/^[A-Za-z\d]+$/.test(value)) {
        level.value.push('low')
        level.value.push('middle')
      } else if (
          /^[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、\d]+$/.test(
              value
          )
      ) {
        level.value.push('low')
        level.value.push('middle')
      } else if (
          /^[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、A-Za-z]+$/.test(
              value
          )
      ) {
        level.value.push('low')
        level.value.push('middle')
      } else if (
          /^[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、A-Za-z\d]+$/.test(
              value
          )
      ) {
        level.value.push('low')
        level.value.push('middle')
        level.value.push('high')
      }
      console.log(level.value);
    }

    const rules: FormRules = {
      newPassword: [
        {
          required: true,
          trigger: ['input', 'blur'],
          message: '请输入密码'
        }
      ],
      password: [
        {
          required: true,
          message: '请输入密码'
        }
      ],
      reenteredPassword: [
        {
          required: true,
          message: '请再次输入密码',
          trigger: ['input', 'blur']
        },
        {
          validator: validatePasswordStartWith,
          message: '两次密码输入不一致',
          trigger: 'input'
        },
        {
          validator: validatePasswordSame,
          message: '两次密码输入不一致',
          trigger: ['blur', 'password-input']
        }
      ]
    }
    return {
      formRef,
      rPasswordFormItemRef,
      model: modelRef,
      rules,
      level,
      handlePasswordInput () {
        checkPassword(modelRef.value.newPassword)
        if (modelRef.value.reenteredPassword) {
          rPasswordFormItemRef.value?.validate({ trigger: 'password-input' })
        }
      },
      handleValidateButtonClick (e: MouseEvent) {
        e.preventDefault()
        formRef.value?.validate((errors) => {
          if (!errors) {
            message.success('修改成功')
          } else {
            console.log(errors)
            message.error('修改失败')
          }
        })
      }
    }
  }
})
</script>

<style lang="scss">
.show_pwd {
  cursor: pointer;
  user-select: none;
  padding-right: 5px;
}
.intensity {
  .psdText {
    font-size: 14px;
    margin-right: 10px;
  }
  .line {
    display: inline-block;
    width: 48px;
    height: 4px;
    background: #d8d8d8;
    border-radius: 3px;
    margin-right: 8px;
    &.low {
      background: #f4664a;
    }
    &.middle {
      background: #ffb700;
    }
    &.high {
      background: #2cbb79;
    }
  }
  .level {
    margin: 0 16px 0 8px;
  }
  .warningtext {
    color: #5a5a5a;
    font-size: 12px;
    margin-top: 5px;
  }
}

</style>